package org.taobao.ibatiside.ui.wizard;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.dialogs.OpenTypeSelectionDialog;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;

public class TypeSelectionCellEditor extends DialogCellEditor {
	private final IJavaProject project;
	private final int category;
	private Label typeLabel;
	private String type;
	public TypeSelectionCellEditor(String type, Composite parent, IJavaProject project, int category) {
		super(parent, SWT.NONE);
		this.project = project;
		this.category = category;
		this.type = type;
	}
	protected Control createContents(Composite cell) {
		typeLabel = new Label(cell, SWT.LEFT);
		typeLabel.setFont(cell.getFont());
		typeLabel.setBackground(cell.getBackground());
		typeLabel.setText(StringUtils.defaultString(type));
		return typeLabel;
	}
	@Override
	protected Object openDialogBox(Control cellEditorWindow) {
		assert (project != null);
		IJavaSearchScope scope = SearchEngine
				.createJavaSearchScope(new IJavaElement[] { project });
		OpenTypeSelectionDialog open_dialog = new OpenTypeSelectionDialog(
				cellEditorWindow.getShell(), false, PlatformUI.getWorkbench()
						.getProgressService(), scope, category);
		open_dialog.create();
		if (open_dialog.open() == OpenTypeSelectionDialog.OK) {
			return (IType) open_dialog.getFirstResult();
		}
		return null;
	}

	@Override
	protected void updateContents(Object value) {
		if (typeLabel == null || value==null) {
			return;
		}
		typeLabel.setText(((IType)value).getFullyQualifiedName());
	}

}
